<template>
	<view class="data-page">
		<!-- 比赛信息 -->
		<view class="match-section">
			<!-- 主队 -->
			<view class="team-box home-team">
				<text class="team-title">主队</text>
				<view class="team-select" @tap="showHomeTeamSelect">
					<text>{{ homeTeam ? homeTeam.name : '选择球队' }}</text>
					<text class="arrow">›</text>
				</view>
				<input type="number" v-model="homeScore" class="score-input" placeholder="0" />
			</view>

			<!-- VS标志 -->
			<view class="vs-box">
				<text class="vs-text">VS</text>
			</view>

			<!-- 客队 -->
			<view class="team-box away-team">
				<text class="team-title">客队</text>
				<input class="team-input" v-model="awayTeamName" placeholder="输入对手球队名称" />
				<input type="number" v-model="awayScore" class="score-input" placeholder="0" />
			</view>
		</view>

		<!-- 比赛详情 -->
		<view class="match-detail-section">
			<view class="detail-row">
				<!-- 比赛时间和地点 -->
				<view class="detail-item">
					<text class="label">比赛时间</text>
					<picker mode="date" :value="matchTime" @change="onDateChange">
						<view class="picker-value">{{ matchTime || '请选择日期' }}</view>
					</picker>
				</view>

				<view class="detail-item">
					<text class="label">比赛地点</text>
					<input class="detail-input" v-model="location" placeholder="请输入比赛地点" />
				</view>
			</view>

			<view class="detail-row">
				<!-- 天气和备注 -->
				<view class="detail-item">
					<text class="label">天气情况</text>
					<picker :range="weatherOptions" :value="weatherIndex" @change="onWeatherChange">
						<view class="picker-value">{{ weatherOptions[weatherIndex] || '请选择天气' }}</view>
					</picker>
				</view>

				<view class="detail-item">
					<text class="label">备注说明</text>
					<input class="detail-input" v-model="remark" placeholder="请输入备注说明" />
				</view>
			</view>
		</view>

		<!-- 出勤人员 -->
		<view class="attendance-section">
			<view class="section-header">
				<text class="section-title">出勤人员</text>
				<text class="add-btn" @tap="showMemberSelect">添加成员</text>
				<text class="selected-count">已选择 {{ selectedMembers.length }} 人</text>
			</view>
			<view class="member-list">
				<view class="member-item" v-for="member in selectedMembersList" :key="member.id">
					<view class="member-info">
						<image class="member-avatar" :src="member.avatar || '/static/avatars/default-avatar.jpg'" mode="aspectFill"></image>
						<text class="member-name">{{ member.name }}</text>
					</view>
					<view class="stats-input">
						<view class="input-item">
							<text class="label">进球</text>
							<input type="number" v-model="member.goals" class="number-input" />
						</view>
						<view class="input-item">
							<text class="label">助攻</text>
							<input type="number" v-model="member.assists" class="number-input" />
						</view>
						<view class="input-item">
							<text class="label">射门</text>
							<input type="number" v-model="member.shots" class="number-input" />
						</view>
						<view class="input-item">
							<text class="label">射正</text>
							<input type="number" v-model="member.shotsOnTarget" class="number-input" />
						</view>
						<view class="input-item">
							<text class="label">犯规</text>
							<input type="number" v-model="member.fouls" class="number-input" />
						</view>
					</view>
					<text class="remove-btn" @tap="removeMember(member)">×</text>
				</view>
			</view>
		</view>

		<!-- 底部按钮 -->
		<view class="bottom-button">
			<button class="submit-btn" @tap="submitData">提交数据</button>
		</view>

		<!-- 球队选择弹窗 -->
		<uni-popup ref="teamPopup" type="bottom">
			<view class="team-popup">
				<view class="popup-header">
					<text class="title">选择球队</text>
					<text class="close" @tap="closeTeamPopup">×</text>
				</view>
				<scroll-view class="team-list" scroll-y>
					<view class="team-item" v-for="team in myTeams" :key="team.id"
						:class="{ selected: isTeamSelected(team.id) }" @tap="selectHomeTeam(team)">
						<image class="team-logo" :src="team.logo || '/static/avatars/default-avatar.jpg'"
							mode="aspectFill"></image>
						<text class="team-name">{{ team.name }}</text>
						<text class="check-icon" v-if="isTeamSelected(team.id)">✓</text>
					</view>
				</scroll-view>
				<view class="popup-footer">
					<button class="create-btn" @tap="createTeam">创建新球队</button>
				</view>
			</view>
		</uni-popup>

		<!-- 成员选择弹窗 -->
		<uni-popup ref="memberPopup" type="bottom">
			<view class="member-popup">
				<view class="popup-header">
					<text class="title">选择成员</text>
					<text class="close" @tap="closeMemberPopup">×</text>
				</view>
				<scroll-view class="member-list" scroll-y>
					<view class="member-item" v-for="member in teamMembers" :key="member.id"
						:class="{ selected: isSelected(member.id) }" @tap="toggleMember(member)">
						<image class="member-avatar"
							:src="member.sysUser.avatar || '/static/avatars/default-avatar.jpg'" mode="aspectFill">
						</image>
						<text class="member-name">{{ member.sysUser.nickName }}</text>
						<text class="check-icon" v-if="isSelected(member.id)">✓</text>
					</view>
				</scroll-view>
				<view class="popup-footer">
					<button class="confirm-btn" @tap="confirmSelection">确定</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import {
		myCreateTeam
	} from '@/api/youqiu/team'
	import {
		listMembers
	} from '@/api/youqiu/members'
	import {
		getActivity
	} from '@/api/youqiu/activity.js'
	import {
		addMatchRecord,
		getRecordByActivityId,
		updateMatchRecord
	} from '@/api/data/matchRecord.js'

	export default {
		data() {
			return {
				activityId: '',
				homeTeam: null,
				awayTeamName: '',
				myTeams: [],
				teamMembers: [],
				selectedMembers: [],
				selectedMembersList: [], // 包含详细信息的已选成员列表
				tempSelectedMembers: [], // 临时存储选择的成员ID
				homeScore: '',
				awayScore: '',
				activityTeamId: '', // 当前活动的球队ID
				matchTime: '',
				location: '',
				weatherOptions: ['晴天', '多云', '阴天', '小雨', '大雨', '雷雨', '雪'],
				weatherIndex: 0,
				remark: '',
				recordId: null, // 记录ID，用于判断是新增还是更新
			}
		},

		onLoad(options) {
			if (options.id) {
				this.activityId = options.id
				this.getRecordByActivityId(this.activityId)
				this.getActivityDetail(options.id)
				this.loadMyTeams()
			}
		},

		methods: {
			async getRecordByActivityId(activityId) {
				try {
					const res = await getRecordByActivityId(activityId)
					console.log('getRecordByActivityId', res)
					if (res.code === 200 && res.data) {
						// 记录ID
						this.recordId = res.data.id
						// 回填比分
						this.homeScore = res.data.homeScore.toString()
						this.awayScore = res.data.awayScore.toString()
						// 回填比赛信息
						this.matchTime = res.data.matchTime?.split(' ')[0] || ''
						this.location = res.data.location || ''
						this.weatherIndex = this.weatherOptions.indexOf(res.data.weather) > -1 
							? this.weatherOptions.indexOf(res.data.weather) 
							: 0
						this.remark = res.data.remark || ''
						// 回填球队信息
						if (res.data.homeTeamId) {
							const team = this.myTeams.find(t => t.id === res.data.homeTeamId)
							if (team) {
								this.selectHomeTeam(team)
							}
						}
						this.awayTeamName = res.data.awayTeamName || ''
						
						// 回填队员数据
						if (res.data.playerMatchStatsList?.length) {
							this.selectedMembers = res.data.playerMatchStatsList.map(p => p.memberId)
							this.selectedMembersList = res.data.playerMatchStatsList.map(p => ({
								id: p.memberId,
								userId: p.userId,
								name: p.sysUser.nickName,
								avatar: p.sysUser.avatar,
								goals: p.goals.toString(),
								assists: p.assists.toString(),
								shots: p.shots.toString(),
								shotsOnTarget: p.shotsOnTarget.toString(),
								fouls: p.fouls.toString()
							}))
							// 设置临时选择状态，用于成员选择弹框
							this.tempSelectedMembers = [...this.selectedMembers]
						}
					}
				} catch (error) {
					console.error('获取比赛记录失败:', error)
				}
			},
			async getActivityDetail(activityId) {
				try {
					const res = await getActivity(activityId)
					if (res.code === 200) {
						this.activityTeamId = res.data.teamId
						// 如果有球队ID，自动选中对应的球队
						if (this.activityTeamId && this.myTeams.length > 0) {
							const team = this.myTeams.find(t => t.id === this.activityTeamId)
							if (team) {
								this.selectHomeTeam(team)
							}
						}
					}
				} catch (error) {
					console.error('获取活动详情失败:', error)
				}
			},

			isTeamSelected(teamId) {
				return this.homeTeam?.id === teamId
			},

			async loadMyTeams() {
				try {
					const res = await myCreateTeam()
					if (res.code === 200) {
						this.myTeams = res.data
						// 如果已经取到活动的球队ID，自动选中对应的球队
						if (this.activityTeamId) {
							const team = this.myTeams.find(t => t.id === this.activityTeamId)
							if (team) {
								this.selectHomeTeam(team)
							}
						}
					}
				} catch (error) {
					console.error('获取球队列表失败:', error)
					uni.showToast({
						title: '获取球队列表失败',
						icon: 'none'
					})
				}
			},

			showHomeTeamSelect() {
				this.$refs.teamPopup.open()
			},

			closeTeamPopup() {
				this.$refs.teamPopup.close()
			},

			async selectHomeTeam(team) {
				this.homeTeam = team
				await this.loadTeamMembers(team.id)
				this.closeTeamPopup()
			},

			async loadTeamMembers(teamId) {
				try {
					const res = await listMembers({
						teamId
					})
					if (res.code === 200) {
						this.teamMembers = res.rows
					}
				} catch (error) {
					console.error('获取球队成员失败:', error)
				}
			},

			showMemberSelect() {
				if (!this.homeTeam) {
					uni.showToast({
						title: '请选择主队',
						icon: 'none'
					})
					return
				}
				// 如果已有选中的成员，设置临时选择状态
				if (this.selectedMembers.length > 0) {
					this.tempSelectedMembers = [...this.selectedMembers]
				}
				this.$refs.memberPopup.open()
			},

			closeMemberPopup() {
				this.$refs.memberPopup.close()
			},

			isSelected(memberId) {
				return this.tempSelectedMembers.includes(memberId)
			},

			toggleMember(member) {
				const index = this.tempSelectedMembers.indexOf(member.id)
				if (index > -1) {
					this.tempSelectedMembers.splice(index, 1)
				} else {
					this.tempSelectedMembers.push(member.id)
				}
			},

			confirmSelection() {
				this.selectedMembers = [...this.tempSelectedMembers]
				this.selectedMembersList = this.teamMembers
					.filter(member => this.selectedMembers.includes(member.id))
					.map(member => ({
						id: member.id,
						userId: member.sysUser.userId,
						name: member.sysUser.nickName,
						avatar: member.sysUser.avatar,
						goals: '0',
						assists: '0',
						shots: '0',
						shotsOnTarget: '0',
						fouls: '0'
					}))
				this.closeMemberPopup()
			},

			removeMember(member) {
				const index = this.selectedMembersList.findIndex(m => m.id === member.id)
				if (index > -1) {
					this.selectedMembersList.splice(index, 1)
					this.selectedMembers = this.selectedMembers.filter(id => id !== member.id)
				}
			},

			createTeam() {
				uni.navigateTo({
					url: '/pages/team/create'
				})
			},

			async submitData() {
				if (!this.homeTeam) {
					uni.showToast({
						title: '请选择主队',
						icon: 'none'
					})
					return
				}

				if (!this.awayTeamName) {
					uni.showToast({
						title: '请输入客队名称',
						icon: 'none'
					})
					return
				}

				if (this.homeScore === '' || this.awayScore === '') {
					uni.showToast({
						title: '请输入比分',
						icon: 'none'
					})
					return
				}

				let data = {
					id: this.recordId,
					activityId: this.activityId,
					homeTeamId: this.homeTeam.id,
					awayTeamName: this.awayTeamName,
					homeScore: Number(this.homeScore),
					awayScore: Number(this.awayScore),
					matchResult: this.getMatchResult(),
					matchTime: this.matchTime,
					location: this.location,
					weather: this.weatherOptions[this.weatherIndex],
					remark: this.remark,
					playerMatchStatsList: this.selectedMembersList.map(member => ({
						memberId: member.id,
						userId: member.userId,
						sysUser: {
							userId: member.userId,
							nickName: member.name,
							avatar: member.avatar
						},
						goals: Number(member.goals) || 0,
						assists: Number(member.assists) || 0,
						shots: Number(member.shots) || 0,
						shotsOnTarget: Number(member.shotsOnTarget) || 0,
						fouls: Number(member.fouls) || 0
					}))
				}

				try {
					const res = await (this.recordId ? updateMatchRecord(data) : addMatchRecord(data))
					if (res.code === 200) {
						uni.showToast({
							title: this.recordId ? '更新成功' : '提交成功',
							icon: 'success'
						})
						setTimeout(() => {
							uni.redirectTo({
								url: '/pages/activity/history'
							})
						}, 1500)
					}
				} catch (error) {
					console.error('提交数据失败:', error)
					uni.showToast({
						title: '提交失败',
						icon: 'none'
					})
				}
			},

			getMatchResult() {
				const homeScore = Number(this.homeScore)
				const awayScore = Number(this.awayScore)
				if (homeScore > awayScore) return 1
				if (homeScore < awayScore) return 2
				return 3
			},

			onDateChange(e) {
				this.matchTime = e.detail.value
			},

			onWeatherChange(e) {
				this.weatherIndex = e.detail.value
			},
		}
	}
</script>

<style lang="scss" scoped>
	.data-page {
		min-height: 100vh;
		background: #f5f5f5;
		padding: 20rpx;
		padding-bottom: 120rpx;
	}

	.match-section {
		background: #fff;
		border-radius: 12rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
		display: flex;
		align-items: flex-start;
		justify-content: space-between;

		.team-box {
			flex: 1;
			display: flex;
			flex-direction: column;
			align-items: center;

			.team-title {
				font-size: 28rpx;
				color: #666;
				margin-bottom: 20rpx;
			}

			.team-select,
			.team-input {
				width: 100%;
				height: 80rpx;
				line-height: 80rpx;
				padding: 0 30rpx;
				background: #f5f5f5;
				border-radius: 8rpx;
				margin-bottom: 20rpx;
				text-align: center;
			}

			.team-select {
				display: flex;
				justify-content: space-between;
				align-items: center;
			}

			.score-input {
				width: 100rpx;
				height: 70rpx;
				background: #f5f5f5;
				border-radius: 8rpx;
				text-align: center;
				font-size: 28rpx;
				font-weight: bold;
			}

			.create-btn {
				width: 100%;
				background: #4CAF50;
				color: #fff;
				font-size: 28rpx;
				height: 80rpx;
				line-height: 80rpx;
			}
		}

		.vs-box {
			padding: 0 20rpx;
			display: flex;
			align-items: center;
			height: 160rpx;

			.vs-text {
				font-size: 32rpx;
				font-weight: bold;
				color: #666;
			}
		}
	}

	.match-detail-section {
		background: #fff;
		border-radius: 12rpx;
		padding: 20rpx;
		margin-bottom: 20rpx;

		.detail-row {
			display: flex;
			justify-content: space-between;
			margin-bottom: 20rpx;

			&:last-child {
				margin-bottom: 0;
			}

			.detail-item {
				flex: 1;
				margin-right: 20rpx;

				&:last-child {
					margin-right: 0;
				}

				.label {
					font-size: 26rpx;
					color: #666;
					margin-bottom: 8rpx;
					display: block;
				}

				.detail-input,
				.picker-value {
					width: 100%;
					height: 70rpx;
					line-height: 70rpx;
					padding: 0 20rpx;
					background: #f5f5f5;
					border-radius: 8rpx;
					font-size: 26rpx;
				}
			}
		}
	}

	.attendance-section {
		background: #fff;
		border-radius: 12rpx;
		padding: 30rpx;

		.section-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 20rpx;

			.section-title {
				font-size: 28rpx;
				color: #666;
			}

			.add-btn {
				font-size: 24rpx;
				color: #4CAF50;
				padding: 4rpx 12rpx;
				border: 1rpx solid #4CAF50;
				border-radius: 24rpx;
				margin-left: auto;
				margin-right: 20rpx;
			}

			.selected-count {
				font-size: 24rpx;
				color: #4CAF50;
			}
		}

		.member-list {
			width: 100%;

			.member-item {
				display: flex;
				align-items: flex-start;
				padding: 20rpx;
				border-bottom: 1rpx solid #eee;
				position: relative;
				width: 100%;

				.member-info {
					display: flex;
					flex-direction: column;
					align-items: center;
					width: 120rpx;
					margin-right: 20rpx;

					.member-avatar {
						width: 60rpx;
						height: 60rpx;
						border-radius: 50%;
						margin-bottom: 10rpx;
					}

					.member-name {
						font-size: 28rpx;
						color: #666;
						text-align: center;
						width: 100%;
						overflow: hidden;
						text-overflow: ellipsis;
						white-space: nowrap;
					}
				}

				.stats-input {
					flex: 1;
					display: grid;
					grid-template-columns: repeat(5, 1fr);
						gap: 20rpx;
						margin-left: 20rpx;

					.input-item {
						display: flex;
						flex-direction: column;
						align-items: center;

						.label {
							font-size: 24rpx;
							color: #666;
							margin-bottom: 8rpx;
						}

						.number-input {
							width: 80rpx;
							height: 60rpx;
							background: #f5f5f5;
							border-radius: 6rpx;
							text-align: center;
							font-size: 28rpx;
						}
					}
				}

				.remove-btn {
					position: absolute;
					right: 20rpx;
					top: 20rpx;
					padding: 10rpx;
					color: #999;
					font-size: 32rpx;
				}

				&:last-child {
					border-bottom: none;
				}
			}
		}
	}

	.bottom-button {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		padding: 20rpx;
		background: #fff;
		border-top: 1rpx solid #eee;

		.submit-btn {
			background: #4CAF50;
			color: #fff;
			border-radius: 44rpx;
		}
	}

	.team-popup {
		background: #fff;
		border-radius: 20rpx 20rpx 0 0;
		padding: 30rpx;

		.popup-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 30rpx;

			.title {
				font-size: 32rpx;
				font-weight: bold;
			}

			.close {
				font-size: 40rpx;
				color: #999;
				padding: 10rpx;
			}
		}

		.team-list {
			max-height: 600rpx;

			.team-item {
				display: flex;
				align-items: center;
				padding: 20rpx 0;
				border-bottom: 1rpx solid #eee;

				&:last-child {
					border-bottom: none;
				}

				.team-logo {
					width: 80rpx;
					height: 80rpx;
					border-radius: 8rpx;
					margin-right: 20rpx;
				}

				.team-name {
					font-size: 28rpx;
					color: #333;
				}
			}
		}

		.popup-footer {
			padding-top: 20rpx;
			border-top: 1rpx solid #eee;
			margin-top: 20rpx;

			.create-btn {
				background: #4CAF50;
				color: #fff;
				border-radius: 44rpx;
				height: 88rpx;
				line-height: 88rpx;
				font-size: 32rpx;
			}
		}
	}

	.member-popup {
		background: #fff;
		border-radius: 20rpx 20rpx 0 0;
		padding: 30rpx;
		max-height: 80vh;
		display: flex;
		flex-direction: column;

		.member-list {
			flex: 1;
			overflow-y: auto;

			.member-item {
				display: flex;
				align-items: center;
				padding: 20rpx;
				border-bottom: 1rpx solid #eee;
				height: 88rpx;

				&.selected {
					background: #f0f9f0;
					.member-name {
						color: #4CAF50;
					}
				}

				.member-avatar {
					width: 60rpx;
					height: 60rpx;
					border-radius: 50%;
					margin-right: 20rpx;
				}

				.member-name {
					font-size: 28rpx;
					color: #333;
					flex: 1;
				}

				.check-icon {
					margin-left: auto;
					color: #4CAF50;
					font-size: 32rpx;
					padding: 0 20rpx;
				}
			}
		}

		.popup-footer {
			padding-top: 20rpx;

			.confirm-btn {
				background: #4CAF50;
				color: #fff;
				border-radius: 44rpx;
				height: 88rpx;
				line-height: 88rpx;
				font-size: 32rpx;
			}
		}
	}
</style>